package org.hxzon.project;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

public class SpringJdbcDao {
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }

    public NamedParameterJdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    //row mapper
    public static <M> RowMapper<M> buildBeanRowMapper(Class<M> clazz) {
        return new MyBeanPropertyRowMapperEx<M>(clazz);
    }

    //param
    public SqlParameterSource buildMapParams(Object... params) {
        if (params == null || params.length == 0) {
            return null;
        }
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        for (int i = 0; i < params.length; i += 2) {
            paramSource.addValue((String) params[i], params[i + 1]);
        }
        return paramSource;
    }

    public SqlParameterSource buildBeanParams(Object param) {
        return new BeanPropertySqlParameterSource(param);
    }

    // sql
    public void execute(String sql, SqlParameterSource param) {
        this.jdbcTemplate.update(sql, param);
    }

    public long count(String sql, SqlParameterSource param) {
        return this.jdbcTemplate.queryForLong(sql, param);
    }

    public <M> List<M> queryList(String sql, SqlParameterSource param, RowMapper<M> mapper) {
        return this.jdbcTemplate.query(sql, param, mapper);
    }

    public <M> M queryOne(String sql, SqlParameterSource param, RowMapper<M> mapper) {
        return this.jdbcTemplate.queryForObject(sql, param, mapper);
    }

    //uuid
    public String buildUuid() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }
}
